package aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect //表示这是一个切面类
@Component //扫描包,产生bean对象注入到Ioc容器中
public class TransactionAspect {
    private static final Logger log = LoggerFactory.getLogger(TransactionAspect.class);

//    @Before(value="execution(* service..*.*(..))")
//    private void before(JoinPoint jp){
//        log.info("【TransactionAspect前置增强】模拟打开数据库连接并开启事务...");
//        log.info("SqlSession sqlSession = MyBatisUtil.createSqlSession(false);");
//    }
//
//    /**
//     *最终增强-执行关闭数据库资源
//     */
//    @AfterReturning(value="execution(* service..*.*(..))",returning = "result")
//    public void afterReturning(JoinPoint jp,Object result){
//        log.info("【TransactionAspect后置增强】模拟正常完成义务提交事务...");
//        log.info("session.commit();");
//    }
//
//    /**
//     *异常抛出增强-执行关闭数据库资源
//     */
//    @AfterThrowing(value = "execution(* service..*.*(..))",throwing = "e")
//    public void afterThrowing(JoinPoint jp,Throwable e){
//        log.info("【TransactionAspect最终增强】模拟业务异常回滚事务,异常信息为:"+e.getMessage());
//        log.info("MyBatisUtil.closeSqlSession(sqlSession);");
//    }
//
//    /**
//     *最终增强-执行关闭数据库资源
//     */
//    @After(value = "execution(* service..*.*(..))")
//    public void after(JoinPoint jp){
//        log.info("【TransactionAspect最终增强】模拟业务完成释放资源...");
//        log.info("MyBatisUtil.closeSqlSession(sqlSession);");
//    }

    //定义切入点,方法名则为引用名称
    @Pointcut("execution(* service..*.*(..))")
    public void pt(){}
    //通过方法名进行引用,注意写法类似于调用方法需加小括号
    @Before(value = "pt()")
    private void before(JoinPoint jp){
        log.info("【TransactionAspect前置增强】模拟打开数据库连接并开启事务...");
        log.info("SqlSession sqlSession = MyBatisUtil.createSqlSession(false);");
    }

    @AfterReturning(value = "pt()",returning = "result")
    public void afterReturning(JoinPoint jp,Object result){
        log.info("【TransactionAspect后置增强】模拟正常完成义务提交事务...");
        log.info("session.commit();");
    }

    /**
     *异常抛出增强-执行关闭数据库资源
     */
    @AfterThrowing(value = "pt()",throwing = "e")
    public void afterThrowing(JoinPoint jp,Throwable e){
        log.info("【TransactionAspect最终增强】模拟业务异常回滚事务,异常信息为:"+e.getMessage());
        log.info("MyBatisUtil.closeSqlSession(sqlSession);");
    }

    @After(value = "pt()")
    public void after(JoinPoint jp){
        log.info("【TransactionAspect最终增强】模拟业务完成释放资源...");
        log.info("MyBatisUtil.closeSqlSession(sqlSession);");
    }
}
